package net.dgg.dggcloud.service.jrcrm.service.visit;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.dgg.dggcloud.core.json.JsonUtil;
import net.dgg.dggcloud.service.common.base.service.BaseService;
import net.dgg.dggcloud.service.common.exception.BizException;
import net.dgg.dggcloud.service.common.util.HttpUtility;
import net.dgg.dggcloud.service.entity.user.User;
import net.dgg.dggcloud.service.jrcrm.entity.business.Business;
import net.dgg.dggcloud.service.jrcrm.entity.cms.TreeBook;
import net.dgg.dggcloud.service.jrcrm.entity.customer.Customer;
import net.dgg.dggcloud.service.jrcrm.service.business.BusinessService;
import net.dgg.dggcloud.service.jrcrm.service.cms.TreeBookService;
import net.dgg.dggcloud.service.jrcrm.service.customer.CustomerService;
import net.dgg.dggcloud.service.service.user.UserService;
import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 销售中心商机service
 */
@Service
public class VisitorService extends BaseService {
	@Resource
	private BusinessService  businessService;
	@Resource
	private CustomerService customerService;
	@Resource
	private UserService  userService;
	@Resource
	private TreeBookService treeBookService;


	@Value("${visit.url}")
	private String visitUrl;

	/**
	 * 查询邀约记录(iboss app)
	 *
	 * @param params
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public String getInvitationsRecord(Map params) {
		Map<String, Object> map = new HashMap<>();
		String result = "";
		String url = visitUrl + "visitor_info/external_list.do";
		try {
			result = HttpUtility.postRest(url, params);
		} catch (Exception e) {
			e.printStackTrace();
			throw new  BizException(e.getMessage(), 10001);
		}
		return result;
	}

	/**
	 * 获取来访地址(iboss app)
	 * 
	 * @return
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public List getProvinceInfo() {
		// 默认禁用的地址也查出来
		List<Map> list = new ArrayList<Map>();
		Map params = new HashMap<>();
		params.put("all", 1);
		String result = "";
		String url = visitUrl + "visitor/app_tree";
		try {
			result = HttpUtility.postRest(url, params);
			Map ma = JsonUtil.json2Obj(result, Map.class);
			if ("0".equals(ma.get("code").toString())) {
				String datas = ma.get("data").toString();// 省级
				list = JsonUtil.json2List(datas, Map.class);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new  BizException(e.getMessage(), 10001);
		}
		return list;
	}

	/**
	 * 获取来访地址(省市)
	 * 
	 * @return
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public List getCityInfo() {
		// 默认禁用的地址也查出来
		List<Map> list = new ArrayList<Map>();
		Map params = new HashMap<>();
		params.put("all", 1);
		String result = "";
		String url = visitUrl + "visitor/app_tree";
		try {
			result = HttpUtility.postRest(url, params);
			Map provinceMap = JsonUtil.json2Obj(result, Map.class);

			if ("0".equals(provinceMap.get("code").toString())) {
				List<Map> provinceList = JsonUtil.json2List(provinceMap.get("data").toString(), Map.class);
				for (Map p : provinceList) {
					p.get("provinceId");
					p.get("province");
					List<Map> cityList = JsonUtil.json2List(p.get("cities").toString(), Map.class);
					for (Map c : cityList) {
						Map provinceCity = new HashMap();
						provinceCity.put("cityId", c.get("cityId"));
						provinceCity.put("city", p.get("province") + "-" + c.get("city"));
						list.add(provinceCity);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new  BizException(e.getMessage(), 10001);
		}
		return list;
	}

	/**
	 * 获取来访地址(根据cityId查询地址)
	 * 
	 * @return
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public List<Map> getVisitorAddress(Map params) {
		List<Map> li = new ArrayList<Map>();
		String result = "";
		String url = visitUrl + "visitor/external_address";
		try {
			result = HttpUtility.postRest(url, params);
			Map ma = JsonUtil.json2Obj(result, Map.class);
			if ("0".equals(ma.get("code").toString())) {
				String address = ma.get("data").toString();
				li = JsonUtil.json2List(address, Map.class);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new  BizException(e.getMessage(), 10001);
		}
		return li;
	}

	/**
	 * 根据商机编号查询商机详情
	 * 
	 * @param businessNo
	 * @return
	 */
	public Business getBusinessEntityBybusinessNo(String businessNo) {
		Business bae = businessService.getBusinessByNo(businessNo);
		return  bae;
	}

	/**
	 * 再次发送短信
	 * 
	 * @return
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public Map reSendSMS(String id, String employeeNo) {
		Map ma = new HashMap<>();
		String url = visitUrl + "visitor_info/external_send_note.do";
		try {
			Map params = new HashMap<>();
			params.put("id", id);
			params.put("employeeNo", employeeNo);
			String result = HttpUtility.postRest(url, params);
			ma = JsonUtil.json2Obj(result, Map.class);
		} catch (Exception e) {
			e.printStackTrace();
			throw new  BizException(e.getMessage(), 10001);
		}
		return ma;
	}

	/**
	 * 取消邀约
	 * 
	 * @return
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public Map cancelInvitations(String id, String askEmployeeNo) {
		Map ma = new HashMap<>();
		String url = visitUrl + "visitor_info/external_cancel.do";
		try {
			Map params = new HashMap<>();
			params.put("id", id);
			params.put("employeeNo", askEmployeeNo);
			String result = HttpUtility.postRest(url, params);
			ma = JsonUtil.json2Obj(result, Map.class);
		} catch (Exception e) {
			e.printStackTrace();
			throw new  BizException(e.getMessage(), 10001);
		}
		return ma;
	}

	/**
	 * 一键预约保存(政企)
	 *
	 * @param params
	 */
//	@Transactional(propagation = Propagation.REQUIRED)
//	public Map sureSubscribe(Map params) {
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		Map<String, Object> map = new HashMap<>();
//
//		String customerName = params.get("customer_name") == null ? "" : params.get("customer_name").toString();
//		String customerPhone = params.get("customer_phone") == null ? "" : params.get("customer_phone").toString();
//		String customerNo = params.get("customer_no") == null ? "" : params.get("customer_no").toString();
//		String customerCardId = params.get("customerCardId") == null ? "" : params.get("customerCardId").toString();
//		String typeControlCode = params.get("typeControlCode") == null ? null
//				: params.get("typeControlCode").toString();
//		String userName = params.get("user_name") == null ? "" : params.get("user_name").toString();
//		String userPhone = params.get("user_phone") == null ? "" : params.get("user_phone").toString();
//		String address = params.get("address") == null ? "" : params.get("address").toString();
//		String we_chat_open_id = params.get("open_id") == null ? "" : params.get("open_id").toString();
//		Long businessId = params.get("businessId") == null ? null : Long.valueOf(params.get("businessId").toString());
//
//		ReservationEntity reservation = new ReservationEntity();
//		BusinessEntity business = businessCommonService.getBusinessEntityById(businessId);
//		UserEntity user = userService.findUserById(business.getFollowerId());
//
//		// 查询一天内同个号码是否有未完成的预约
//		Map findParams = new HashMap();
//		findParams.put("customerPhone", customerPhone);
//		Calendar calendar = Calendar.getInstance();
//		calendar.setTime(new Date());
//		calendar.set(Calendar.HOUR_OF_DAY, 0);
//		calendar.set(Calendar.MINUTE, 0);
//		calendar.set(Calendar.SECOND, 0);
//		Date startDate = calendar.getTime();
//		calendar.set(Calendar.HOUR_OF_DAY, 23);
//		calendar.set(Calendar.MINUTE, 59);
//		calendar.set(Calendar.SECOND, 59);
//		Date endDate = calendar.getTime();
//		findParams.put("startTime", sdf.format(startDate));
//		findParams.put("endTime", sdf.format(endDate));
//
//		List list = reservationDao.findByPhone(findParams);
//		if (list.size() > 0) {
//			map.put("msg", "存在未完成的预约，不能再预约");
//			map.put("status", "fail");
//			return map;
//		}
//
//		reservation.setCreateTime(new Date());
//		reservation.setReStatus("1");
//		reservation.setStatusTime(new Date());
//		reservation.setUserPhone(userPhone);
//		reservation.setUserName(userName);
//		reservation.setUserId(user.getId());
//		reservation.setChannel("3");
//		reservation.setCustomerIdNumber(customerCardId);
//		reservation.setCustomerName(customerName);
//		// reservation.setCustomerNo(customerNo);
//		reservation.setCustomerPhone(customerPhone);
//		reservation.setTypeControlCode(typeControlCode);
//		reservation.setWeChatOpenId(we_chat_open_id);
//		reservation.setAddress(address);
//		reservation.setAppointment(new Date());
//		Long reservatopmId = DggKeyWorker.nextId();
//		reservation.setId(reservatopmId);
//		reservationDao.insert(reservation);
//
//		map.put("id", reservation.getId());
//		map.put("status", "success");
//		map.put("appointment", sdf.format(reservation.getAppointment()));
//		return map;
//	}

	/**
	 * 确认预约
	 * 
	 * @param params
	 * @return
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public Map subscribe(Map params) {
		Map returnMap = new HashMap<>();
		Long userId = Long.parseLong(params.get("userId").toString());
			String customerPhoneId = params.get("contactPhone").toString();
			String businessId = params.get("businessId").toString();
			Map<String, Object> map = new HashMap();
			Business business = businessService.getBusinessById(Long.parseLong(businessId));
			Customer customer = customerService.findCustomerById(business.getCustomerId());
			map.put("type_code", business.getTypeCode());
			User user = userService.getUserById(business.getFollowerId());
			map.put("user_name", user.getName());
			map.put("user_phone", user.getPhone());
			map.put("customer_phone", customerPhoneId);
			map.put("customer_name", customer.getName());
			map.put("customer_no", customer.getNo());
			map.put("typeControlCode", business.getTypeCode());
			map.put("businessId", businessId);
			//returnMap = sureSubscribe(map);// 政企预约

		return returnMap;
	}



	/**
	 *
	 * 根据商机编号,邀请人工号修改上门状态
	 *
	 * @param
	 * @param
	 * @return
	 */
//	public Integer updateVisitorStatus(String businessCode, String businessNo) {
//		if (businessCode.contains("-")) {
//			businessCode = businessCode.split("-")[1];
//		}
//		UserEntity user = userRecorderDAO.findUserEntityByUserLoginName(businessNo);
//		if (user == null) {
//			logger.error("未查询到对应的邀请人！");
//			throw new BusinessAppException("未查询到对应的邀请人！");
//		}
//		Long followerId = userRecorderDAO.findUserEntityByUserLoginName(businessNo).getId();
//		return businessCommonDao.updateVisitorStatusByNo(businessCode, followerId);
//	}

}
